package com.azt.utils;

import javax.websocket.Session;

import net.sf.json.JSONObject;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


/**
 * websorket连接session管理
 * @author 张栋  2016年7月12日上午11:03:50
 */
public class SessionUtils {

	public static Map<String, Session> clients = new ConcurrentHashMap<>();

	public static void put(String relationId, int userCode, Session session) {
		clients.put(getKey(relationId, userCode), session);
	}

	public static Session get(String relationId, int userCode) {
		return clients.get(getKey(relationId, userCode));
	}

	public static void remove(String relationId, int userCode) {
		clients.remove(getKey(relationId, userCode));
	}

	/**
	 * 判断是否有连接
	 * 
	 * @param relationId
	 * @param userCode
	 * @return
	 */
	public static boolean hasConnection(String relationId, int userCode) {
		return clients.containsKey(getKey(relationId, userCode));
	}

	/**
	 * 组装唯一识别的key
	 * 
	 * @param relationId
	 * @param userCode
	 * @return
	 */
	public static String getKey(String relationId, int userCode) {
		return relationId + "_" + userCode;
	}

	
	
	/**
	 * 将数据传回客户端 异步的方式
	 * @param relationId
	 * @param userCode
	 * @param message
	 */
	public static boolean broadcast(String relationId, int userCode, String message) {
		return broadcast(relationId,userCode,message,null);
	}
	
	public static boolean broadcast(int adminid, String message) {
		if(adminid==0)return false;
		return broadcast("test",adminid,message,null);
	}


	
	public static boolean broadcast(String relationId, int userCode, String message,String messagecode) {
		try {
			
			if (SessionUtils.hasConnection(relationId, userCode)) {
				JSONObject mobj = new JSONObject();
				if(messagecode==null){
					mobj.put("code", "0");
				}else{
					mobj.put("code", messagecode);
				}
				mobj.put("msg", message);
				SessionUtils.get(relationId, userCode).getAsyncRemote().sendText(mobj.toString());
				return true;
			} else {
				System.out.println(SessionUtils.getKey(relationId, userCode) + " Connection does not exist");
				return false;
			}
		} catch (Exception e) {
			return true;
		}
		
	}
	
	/**
	 * 发送聊天消息
	 * @author 张栋  2016年7月29日上午9:43:30
	 */
	public static boolean sendmessage(int frompepole,int topeople,String fromname,String message,String code){
		try {
			
			if (SessionUtils.hasConnection("test", topeople)) {
				JSONObject mobj = new JSONObject();
				mobj.put("code", code);
				mobj.put("msg", message);
				mobj.put("from", fromname);
				mobj.put("fromid", frompepole);
				SessionUtils.get("test", topeople).getAsyncRemote().sendText(mobj.toString());
				return true;
			} else {
				System.out.println(SessionUtils.getKey("test", topeople) + " Connection does not exist");
				return false;
			}
		} catch (Exception e) {
			return true;
		}
	}
}